import socket


def read_file(file_name):
    """读取文件内容并返回"""
    try:
        with open(file_name, 'rb') as file:  # with 结束后会自动关闭文件，但是不会捕捉异常
            file_data = file.read()
    except FileNotFoundError as exp:
        print(exp)
    else:
        return file_data


def main():
    """文件下载器-服务器"""
    # 创建并初始化服务器套接字
    server_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_soc.bind(("", 1315))
    server_soc.listen(128)

    # 获取客户端连接
    client_soc, client_addr = server_soc.accept()

    # 接收文件名
    file_name = client_soc.recv(1024)

    # 读取文件内容
    file_data = read_file(file_name)

    if file_data:
        # 返回文件内容给客户端
        client_soc.send(file_data)

    # 关闭客户端套接字
    client_soc.close()

    # 关闭服务器套接字
    server_soc.close()


if __name__ == '__main__':
    main()
